<template>
  <div>
      <el-container style="height: 700px; border: 1px solid #eee">
      <el-header
        style="
          font-size: 40px;
          color: #409eff;
          background-color: rgb(238, 241, 246);
        "
        >---北斗定点智能垃圾分拣机器人产品实时追踪平台---
      </el-header>

      <el-container>
        <el-aside width="100px">
          <i class="el-icon-camera-solid"></i>
        </el-aside>

<el-container>
      <el-main>
    <el-button type="primary" @click="selectPort">Select</el-button>
    <el-button type="primary" @click="openPort">Open</el-button><br>
    <el-button type="primary" @click="closePort">Close</el-button>
    <el-button type="primary" @click="sendData">Send</el-button><br>
    <textarea v-model="outputData" placeholder="D0 D1 D2 D3 D4 D5 D6 D7"></textarea><br />
    <textarea v-model="inputData" readonly></textarea>
      </el-main>

      <el-footer
            style="
              font-size: 20px;
              color: #F56C6C;
              background-color: rgb(238, 241, 246);
            "
            >---串口---
          </el-footer>
      </el-container>
      </el-container>
      </el-container>
  </div>
</template>

<script>
export default {
  data() {
    return {
      port: null,
      reader: null,
      reading: false,
      outputData: "D0 D1 D2 D3 D4 D5 D6 D7",
      inputData: "",
    };
  },
  mounted() {
    if ("serial" in navigator) {
      console.log("Web Serial API supported.");
    } else {
      alert("Your browser does not support Web Serial API.");
    }

    navigator.serial.onconnect = (event) => {
      console.log("Serial port connected:", event.target);
    };

    navigator.serial.ondisconnect = (event) => {
      console.log("Serial port disconnected:", event.target);
    };
  },
  methods: {
    async selectPort() {
      try {
        this.port = await navigator.serial.requestPort();
        console.log("Port selected:", this.port);
      } catch (error) {
        console.error("Error selecting port:", error);
      }
    },
    async openPort() {
      if (!this.port) {
        console.log("No port selected.");
        return;
      }
      try {
        await this.port.open({ baudRate: 115200 });
        this.listenForData();
        console.log("Port opened.");
      } catch (error) {
        console.error("Error opening port:", error);
      }
    },
    async closePort() {
      if (!this.port || !this.port.writable) {
        console.log("No open port to close.");
        return;
      }
      if (this.reading) {
        this.reading = false;
        this.reader?.cancel();
      }
      await this.port.close();
      this.port = null;
      console.log("Port closed.");
    },
    async sendData() {
      if (!this.port || !this.port.writable) {
        console.log("No open port to send data.");
        return;
      }
      try {
        const writer = this.port.writable.getWriter();
        await writer.write(this.parseOutputData());
        writer.releaseLock();
        console.log("Data sent.");
      } catch (error) {
        console.error("Error sending data:", error);
      }
    },
    parseOutputData() {
      const dataStr = this.outputData.replace(/\s+/g, "");
      if (dataStr.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(dataStr)) {
        const byteLength = dataStr.length / 2;
        const outputData = new Uint8Array(byteLength);
        for (let i = 0; i < byteLength; i++) {
          outputData[i] = parseInt(dataStr.substr(i * 2, 2), 16);
        }
        return outputData;
      } else {
        throw new Error("Invalid data format.");
      }
    },
    async listenForData() {
      if (this.reading) {
        console.log("Already listening for data.");
        return;
      }
      while (this.port?.readable && this.reading) {
        this.reader = this.port.readable.getReader();
        try {
          while (this.reading) {
            const { value, done } = await this.reader.read();
            if (done) {
              break;
            }
            this.updateInputData(value);
          }
        } catch (error) {
          console.error("Error reading data:", error);
        } finally {
          this.reader.releaseLock();
        }
      }
    },
    updateInputData(data) {
      const array = new Uint8Array(data);
      const hexStr = Array.from(array)
        .map((byte) => byte.toString(16).toUpperCase().padStart(2, "0"))
        .join(" ");
      this.inputData += `${hexStr} `;
    },
  },
};
</script>

<style scoped>
button,
textarea {
  margin: 1rem;
  margin-bottom: 0;
  padding: 0.5rem;
  width: 20rem;
}

textarea {
  resize: none;
  overflow-y: scroll;
  overflow-x: hidden;
  height: 5rem;
}
.input_underline {
  border-bottom: 1px solid #dbdbdb;
  border-top: 0px;
  border-left: 0px;
  border-right: 0px;
  width: 200px;
  color: #f6931f;
  font-weight: bold;
}

.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #d3dce6;
  color: #333;
  text-align: center;
  line-height: 200px;
}

.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
  line-height: 160px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

</style>
